package com.example.whm;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Activity;
import org.holoeverywhere.app.Application;
import org.holoeverywhere.app.Fragment;
import org.holoeverywhere.app.ProgressDialog;
import org.holoeverywhere.preference.SharedPreferences;
import org.holoeverywhere.widget.AdapterView;
import org.holoeverywhere.widget.AdapterView.OnItemSelectedListener;
import org.holoeverywhere.widget.CheckBox;
import org.holoeverywhere.widget.LinearLayout;
import org.holoeverywhere.widget.ListView;
import org.holoeverywhere.widget.TextView;
import org.holoeverywhere.widget.Toast;

import android.content.Context;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.example.whm.lib.box_Selection;
import com.example.whm.model.Address;
import com.example.whm.model.Box;
import com.example.whm.model.SubscribeItem;
import com.example.whm.model.SubscribeRecord;

public class FourFragmentSubscribe extends Fragment implements OnItemSelectedListener,OnClickListener{

	private AQuery aq; 
	private AQuery aq2;
	
	private String topic;
	Address add;
	List<Box> boxs;
	int num=0;
	int price=0;
	int tag;
	 TextView v;
	 box_Selection mCallback;
	 List<SubscribeRecord> sublist;
	ProgressDialog dialog;
	adapter2 adap2;
	adapter adap;
	adapter3 adap3;
	List<adapter3> adap3_l=new ArrayList<adapter3>();
	TextView num_t;
	 TextView price_t;
	 ListView list;
	List<CheckBox> check_list=new ArrayList<CheckBox>();
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
    	View view = inflater.inflate(R.layout.four_layout_item, container, false); 
    	aq=new AQuery(getActivity());
    	aq2=new AQuery(getActivity(), view);
    	
    	return view;
	}



    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
             mCallback = (box_Selection) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }




	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
		init(3);
		
		
		
	}


  public void init(int t){
	  tag=t;
	  String url="http://"+Whm_app.api_url+":9000/api/buy_box?tag="+t;
	  AjaxCallback<String> cb = new AjaxCallback<String>();        
	  cb.url(url).type(String.class).weakHandler(this, "ui");
	  SharedPreferences sp=((Application)getActivity().getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
  	String cookiename=sp.getString("cookie_name",null);
  	String cookievalue=sp.getString("cookie_value",null);
  	if (cookiename!=null&&cookievalue!=null) {
  		cb.cookie(cookiename,cookievalue);               
	}
	  aq.ajax(cb);	  
  }

  public void ui(String url, String r, AjaxStatus status){
	  
	  System.out.println("ui  s="+r); 
	  if (status.getCode()==200) {
		
		  final String s=r;
		  new Thread( new Runnable() {
			  @Override
			public void run() {
				  // String s1= JSON.parseObject(s).getString("users");
				  
				  String addj= JSON.parseObject(s).getString("add");
				  String listj= JSON.parseObject(s).getString("sublist");
				  add= JSON.parseObject(addj, Address.class);
				  sublist= JSON.parseArray(listj, SubscribeRecord.class);
				  
				  if (list!=null) {
					  num=0;
					  price=0;
				  }
				  
				  num=sublist.size();
				  for(SubscribeRecord s:sublist){
					  //num=num+b.getNum();
					 
					  price=price+s.getSub_price();
					  
				  };
				  
				  getActivity().runOnUiThread(new Runnable() {
					  
					  @Override
					  public void run() {
						  if (list!=null) {
							  show_dialog(false);
							  Whm_app.newl.remove(Integer.valueOf(3));
							  num_t.setText(String.valueOf(num));
							  price_t.setText(String.valueOf(price));
							  List<List<SubscribeRecord>> l= new ArrayList<List<SubscribeRecord>>();
							  l.add(sublist);
							  adap.setList(l);
							  adap.notifyDataSetChanged();
						}else{	
						  
						  
						  aq2.id(R.id.four_layout_progress).gone();
						  aq2.id(R.id.four_layout_line).visible();
						  //System.out.println("four_layout_line================"); 
						
						   list=(ListView) aq2.id(R.id.four_layout_detail_listview).getListView();
						  View v=getActivity().getLayoutInflater().inflate(R.layout.four_layout_header, null);
						  View v2=getActivity().getLayoutInflater().inflate(R.layout.four_layout_footer, null);
						   AQuery a=new AQuery(v);
						   AQuery a2=new AQuery(v2);
						   a.find(R.id.four_layout_pay_s2).enabled(false);
						   a2.find(R.id.four_layout_btn_sure).clicked(FourFragmentSubscribe.this); 
						  a.id(R.id.four_layout_contact_name).text(add.getContact_name());
						  a.id(R.id.four_layout_contact_phone).text(add.getPhone());
						  a.id(R.id.four_layout_contact_addr).text(add.getDetail_address());
						   
						
						  list.addHeaderView(v);
						  list.addFooterView(v2);
						  List<List<SubscribeRecord>> l= new ArrayList<List<SubscribeRecord>>();
						  l.add(sublist);
						   adap=new adapter(l);
						  aq2.id(R.id.four_layout_detail_listview).adapter(adap);
						  //Utility.setListViewHeightBasedOnChildren(list);
						}
					  }
				  });
			  }
		  }).start();
		  
	}
	  
  }

  
  
  
  
  
  
  
  class adapter extends BaseAdapter{

		
	  
		List<List<SubscribeRecord>> list;
		public adapter() {
			super();
			// TODO Auto-generated constructor stub
		}
	   
		
		public adapter(List<List<SubscribeRecord>> list) {
			super();
			this.list = list;
		}

		
		

		public List<List<SubscribeRecord>> getList() {
			return list;
		}


		public void setList(List<List<SubscribeRecord>> list) {
			this.list = list;
		}


		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
		
			//System.out.println("adapter arg0---------------"+arg0);
			if(arg1 == null){
				arg1 = aq.inflate(arg1, R.layout.four_layout_list, arg2);
			}
			
			
			List<SubscribeRecord> i = (List<SubscribeRecord>) getItem(arg0);
			AQuery aq = aq2.recycle(arg1);
			 adap2=new adapter2(i);
			aq.id(R.id.four_layout_list_item_listview).adapter(adap2);
			aq.id(R.id.four_layout_btn_all).clicked(FourFragmentSubscribe.this);
			aq.id(R.id.four_layout_btn_del).clicked(FourFragmentSubscribe.this);
		    aq.id(R.id.four_listview_footview_num).text(String.valueOf(num));
		    aq.id(R.id.four_listview_footview_price).text(String.valueOf(price));
		    
		     num_t = (TextView) aq.id(R.id.four_listview_footview_num).getTextView();
			 num_t.setText(String.valueOf(num));
			  price_t = (TextView) aq.id(R.id.four_listview_footview_price).getTextView();
			 price_t.setText(String.valueOf(price));
		    
		    
		    
			return arg1;
		}
		
		
	}
  
  public void makeMenu(Menu menu, MenuInflater inflater) {
      if (menu instanceof ContextMenu) {
          ((ContextMenu) menu).setHeaderTitle("Context menu title");
      }
      menu.clear();
      inflater.inflate(R.menu.menu, menu);
      for (int i = 0; i < menu.size(); i++) {
          menu.getItem(i).setOnMenuItemClickListener(mOnMenuItemClickListener);
      }
     
  }
  
  private final OnMenuItemClickListener mOnMenuItemClickListener = new OnMenuItemClickListener() {
      @Override
      public boolean onMenuItemClick(MenuItem menuItem) {
          boolean result = false;
          final int id = menuItem.getItemId();
          if (menuItem.getTitle().equals("order")) {
        	  mCallback.show_boxf(0);
		  }
          if (menuItem.getTitle().equals("preorder")) {       
        	  mCallback.show_boxf(1);
          }
          if (menuItem.getTitle().equals("subscribe")) {        	  
        	  mCallback.show_boxf(2);
          }
          //  System.out.println("onMenuItemClick id========="+id);
          return true;
      }
  };
  
  
  class adapter2 extends BaseAdapter{

		
	  List<SubscribeRecord> list;
		public adapter2() {
			super();
			// TODO Auto-generated constructor stub
		}
	   
		
		
		
		
		
		public List<SubscribeRecord> getList() {
			return list;
		}






		public void setList(List<SubscribeRecord> list) {
			this.list = list;
		}






		public adapter2(List<SubscribeRecord> list) {
			super();
			this.list = list;
		}


		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
		
			//System.out.println("adapter2 arg0---------------"+arg0);
			if(arg1 == null){
				arg1 = aq.inflate(arg1, R.layout.four_layout_list_item_sub, arg2);
			}
			
			
			SubscribeRecord i = (SubscribeRecord) getItem(arg0);
			AQuery aq = aq2.recycle(arg1);
			aq.id(R.id.four_layout_item_sub).text(i.getName());
			aq.id(R.id.four_layout_item_sub_price).text(String.valueOf(i.getSub_price()));
			
		    adap3=new adapter3(i.getSub_items());
		    if (!adap3_l.contains(adap3)) {
				adap3_l.add(adap3);
			}
		    aq.id(R.id.four_layout_item_sub_grid).adapter(adap3);
			aq.id(R.id.four_layout_item_sub_check).checked(false);
			aq.id(R.id.four_layout_item_sub_check).clicked(FourFragmentSubscribe.this);
			CheckBox checkb = (CheckBox) aq.id(R.id.four_layout_item_sub_check).getCheckBox();
			checkb.setOnClickListener(FourFragmentSubscribe.this); 
			  //  checkb.setOnCheckedChangeListener(FourFragmentPreorder.this);
			checkb.setTag(arg0);
			if (!check_list.contains(checkb)) {
					check_list.add(checkb);
				}
			return arg1;
		}
		
		
	}
  class adapter3 extends BaseAdapter{

		
		List<SubscribeItem> list;
		public adapter3() {
			super();
			// TODO Auto-generated constructor stub
		}
	   
		
		public adapter3(List<SubscribeItem> list) {
			super();
			this.list = list;
		}


		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
		
			//System.out.println("adapter3 arg0---------------"+arg0);
			if(arg1 == null){
				arg1 = aq.inflate(arg1, R.layout.three_layout_grid_item, arg2);
			}
			
			
			SubscribeItem i = (SubscribeItem) getItem(arg0);

			AQuery aq = aq2.recycle(arg1);
		    aq.id(R.id.three_layout_grid_item_text).text(i.getDetail_date());
			String tbUrl = i.getList().get(0).getEntity().getPre_pic().replace("localhost", Whm_app.api_url);
		
			if(aq.shouldDelay(arg0, arg1, arg2, tbUrl)){
				aq.id(R.id.three_layout_grid_item_imagevie).clear();
			}else{
				aq.id(R.id.three_layout_grid_item_imagevie).image(tbUrl, true, true, 200, R.drawable.ic_launcher, null,0, 0);
			}
			
			
			return arg1;
		}
		
		
	}






@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
		long id) {
	// TODO Auto-generated method stub
	
	int cur=position+1;
	if (cur!=tag) {
		Toast.makeText(getActivity(), cur+" ==="+tag, 1000).show();
		aq.id(R.id.four_layout_line).gone();
		LinearLayout line=(LinearLayout)aq.id(R.id.four_layout_line).getView();
		line.removeAllViews();
		aq.id(R.id.four_layout_progress).visible();
		init(cur);
	}
	
}






@Override
public void onNothingSelected(AdapterView<?> parent) {
	// TODO Auto-generated method stub
	
}


public void show_dialog(boolean b){
	

	if (dialog==null) {
		dialog = new ProgressDialog(getSupportActivity());
	    dialog.setIndeterminate(true);
	    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    dialog.setMessage("post");
	}
	if (b) {
		dialog.show();
	}else{
		dialog.dismiss();
	} 
    
}

boolean is_check=true;
List<String> ids=new ArrayList<String>();
List<SubscribeRecord> ids_box=new ArrayList<SubscribeRecord>();

@Override
public void onClick(View v) {
	// TODO Auto-generated method stub
	switch (v.getId()) {  
    case R.id.four_layout_btn_sure:
    	buy_sure();
    	break;	
    case R.id.four_layout_btn_all:
    	btn_all();
    	break;
    case R.id.four_layout_btn_del:
    	btn_del();
    	break;
    case R.id.four_layout_item_sub_check:
    final CheckBox ch=(CheckBox) v;	
	int pos=(Integer) ch.getTag();
	ch.setFocusable(false);
	ch.setFocusableInTouchMode(false);
	SubscribeRecord box=adap2.getList().get(pos);
	String id=box.getSubscribe_id();
	if (ch.isChecked()) {
		
		if (!ids.contains(id)) {
			ids.add(id);
		}
		if (!ids_box.contains(box)) {
			ids_box.add(box);
		}
	}else{
		ids.remove(id);
		ids_box.remove(box);
	}

	Toast.makeText(getActivity(), id+" "+ids.size()+" "+ids_box.size(), 1000).show();
	break;		
    	
    default:  
        break;  
    }  
}

public void btn_all(){
	
	System.out.println("check_list.size()======="+check_list.size());
	for(final CheckBox checkb:check_list){
		int pos=(Integer) checkb.getTag();
		SubscribeRecord box=adap2.getList().get(pos);
		
		String id=box.getSubscribe_id();
	
		
		if (is_check) {
			 getActivity().runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					checkb.setChecked(true);
					//System.out.println("checkb.isChecked() ======="+checkb.isChecked());
				}
			});
			
			
			
			
			if (!ids.contains(id)) {
				ids.add(id);
			}
			if (!ids_box.contains(box)) {
				ids_box.add(box);
			}
			
		}else{
			 getActivity().runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						checkb.setChecked(false);
						
					}
				});
						
			ids.remove(id);
			ids_box.remove(box);
		}
		
	}
if (is_check) {
		
		is_check=false;
	}else{
		is_check=true;
	}
System.out.println("ids======="+JSONObject.toJSONString(ids));
System.out.println("ids_box.size()======="+ids_box.size());
	
}

public void btn_del(){
	if (!ids.isEmpty()) {
		Map<String, Object> params = new HashMap<String, Object>();
	    params.put("type", 3);
	    params.put("ids", JSONObject.toJSONString(ids));
	  
	    System.out.println("btn_del ids===="+JSON.toJSONString(ids));
	    String url="http://"+Whm_app.api_url+":9000/api/buy_del_func";
	  AjaxCallback<String> cb = new AjaxCallback<String>();        
	  cb.url(url).type(String.class).weakHandler(FourFragmentSubscribe.this, "buy_del_func_result");

	  SharedPreferences sp=((Application)getActivity().getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
	String cookiename=sp.getString("cookie_name",null);
	String cookievalue=sp.getString("cookie_value",null);
	if (cookiename!=null&&cookievalue!=null) {
		cb.cookie(cookiename,cookievalue);               
	}else{
		
	}
	
	show_dialog(true);	
	cb.params(params);

	aq.ajax(cb);
	}else{
		
		
		Toast.makeText(getActivity(), "no selected", 1000).show();
	}
	
}

public void buy_del_func_result(String url, String r, AjaxStatus status){
	show_dialog(false);
	 if (status.getCode()==200) {
		 adap2.getList().removeAll(ids_box);
		
		// check_list.clear();
		 System.out.println("adap2.getList() "+JSONObject.toJSONString(adap2.getList()));
		 System.out.println("ids_box "+JSONObject.toJSONString(ids_box));
		 
		  getActivity().runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					 
					 
					 num=0;
					 price=0;
					 for(SubscribeRecord b: adap2.getList()){
						  num=num+adap2.getList().size();
						  price=price+b.getSub_price();
						  
					  };
					 num_t.setText(String.valueOf(num));
					 price_t.setText(String.valueOf(price));
					 num_t.invalidate();
					 price_t.invalidate();
					
				
					 Toast.makeText(getActivity(), "adap2.getList().size()="+adap2.getList().size()+" num="+num+" price="+price, 3000).show();
					// adap2.notifyDataSetChanged();
					check_list.clear();
					ids.clear();
					ids_box.clear();
					for(adapter3 adp3:adap3_l){ 
						adp3.notifyDataSetChanged();
					}
					//adap3.notifyDataSetChanged();
					adap2.notifyDataSetChanged();
					adap.notifyDataSetChanged();
				
				}
			});
		
			 
		  
	 }else{
		 Toast.makeText(getActivity(), "parse error", 1000).show();
	 }
	
	
}





public void buy_sure(){
	 show_dialog(true);
	  Map<String, Object> params = new HashMap<String, Object>();
	    params.put("type", 1);
	    params.put("tag", 3);
	    params.put("address_id", add.getId());
	  
	    System.out.println("buy_sure===="+JSON.toJSONString(params));
	    String url="http://"+Whm_app.api_url+":9000/api/buy_sure_func";
	  AjaxCallback<String> cb = new AjaxCallback<String>();        
	  cb.url(url).type(String.class).weakHandler(this, "sure_func_result");
	  SharedPreferences sp=((Application)getActivity().getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
	String cookiename=sp.getString("cookie_name",null);
	String cookievalue=sp.getString("cookie_value",null);
	if (cookiename!=null&&cookievalue!=null) {
		cb.cookie(cookiename,cookievalue);               
	}
	  cb.params(params);
	  aq.ajax(cb);
	
}

public void sure_func_result(String url, String r, AjaxStatus status){
	  show_dialog(false);
	  System.out.println("sure_func_result========="+r);
	//  System.out.println("sure_func_result status.getCode()========="+status.getCode());
	//  System.out.println("sure_func_result url========="+url);
	  if (status.getCode()==200) {
		
		 String re=JSON.parseObject(r).getString("result");
		 if (re.equals("ok")) {
		    refresh_list();
		}else if(re.equals("login_error")){
			
			Toast.makeText(getActivity(), String.valueOf("login error,please again"), 1000).show();
		}
		 
	 }else{		 
		 Toast.makeText(getActivity(), String.valueOf("post error,please again"), 1000).show();
	 }
}

public void refresh_list(){
	  getActivity().runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				 
				 num=0;
					price=0;
					 num_t.setText(String.valueOf(num));
					 price_t.setText(String.valueOf(price));
				 adap2.getList().clear();
				 adap2.notifyDataSetChanged();
				 adap.notifyDataSetChanged();
			
			}
		});
	
}

public void refresh(){
	show_dialog(true);
	init(3);
	
}

    
 
}
